import re
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from goods.models import SKU
from .models import User, Address
from celery_tasks.email.tasks import send_verify_email


class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""

    password2 = serializers.CharField(label='密码2', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='JWT token登录状态', read_only=True)

    """
    序列化器中需要的所有字段: 'id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
    模型中已有字段: id', 'username', 'mobile', 'password'
    需要进行反序列化的字段: 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
    需要进行序列化的字段:  'id', 'username', 'mobile', 'token'
    """

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'token']

        extra_kwargs = {  # 对序列化器中的字段进行额外配置
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {  # 自定义反序列化校验错误信息
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,  # 只做反序列化
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """对手机号单独追加校验逻辑"""

        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号码格式错误')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请勾选同意协议')
        return value

    def validate(self, attrs):
        """对两个密码进行校验"""
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError('两次密码不一致')

        # 校验验证码
        mobile = attrs.get('mobile')
        # 创建redis连接
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 向redis存储数据时,都是以字符串的格式进行存储,将来取出来后,都会变成'bytes'类型:str
        if not real_sms_code:
            raise serializers.ValidationError('验证码过期')
        # 需要转换为str类型
        if real_sms_code.decode() != attrs.get('sms_code'):
            raise serializers.ValidationError('验证码错误')

        return attrs

    def create(self, validated_data):
        """重写序列化器的保存方法把多余数据移除"""
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        password = validated_data.pop('password')  # 把字典中的password移除

        user = User(**validated_data)
        user.set_password(password)  # 对密码进行加密后再赋值给user模型对象的password属性
        user.save()

        # 手动生成JWT token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数
        payload = jwt_payload_handler(user)  # 通过传入user对象生成jwt 载荷部分
        token = jwt_encode_handler(payload)  # 传入payload 生成token
        # 给user 模型对象多增加一个token属性,再给序列化器多增加token字段只做序列化
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """
    设置邮箱序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'email')
        # 因为email字段在模型定义中,设置的可以为空,那么ModelSerializer自动生成字段时,字段可以为空,所以默认值为False,需要手动设为True
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()

        # 生成验证链接
        verify_url = instance.generate_verify_email_url()
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)


class UserBrowseHistorySerializer(serializers.Serializer):
    """保存浏览记录"""
    sku_id = serializers.IntegerField(label='sku商品id', min_value=1)

    def validate_sku_id(self, value):
        """追加额外校验逻辑"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')
        return value

    def create(self, validated_data):
        """重写此方法把浏览记录存储到redis数据库"""
        sku_id = validated_data.get('sku_id')
        # 获取当前的用户user
        user = self.context['request'].user
        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 创建管道对象
        pl = redis_conn.pipeline()
        # 先去重 lrem()
        pl.lrem('history_%s' % user.id, 0, sku_id)
        # 添加 lpush()
        pl.lpush('history_%s' % user.id, sku_id)
        # 截取前5个  ltrim()
        pl.ltrim('history_%s' % user.id, 0, 4)
        # 执行管道
        pl.execute()
        # 返回
        return validated_data
